package com.refusea.train.domain.helper

import com.refusea.train.config.mvc.WebSession
import com.refusea.train.domain.cache.CourseCache
import com.refusea.train.domain.cache.UserCache
import com.refusea.train.domain.entity.Course
import com.refusea.train.domain.entity.User.Role.PRINCIPAL
import com.refusea.train.domain.ex.BizEx
import com.refusea.train.mapper.CourseMapper
import com.refusea.train.mapper.OrderMapper
import org.springframework.stereotype.Component

/**
 * @author Zhang Yan 2024/4/3
 **/
@Component
class CourseHelper(
    private val courseMapper: CourseMapper,
    private val orderMapper: OrderMapper,
    private val userCache: UserCache,
    private val courseCache: CourseCache,
) {

    fun list(): List<Course> {
        return courseMapper.list(WebSession.user().schoolId)
    }

    // valid course: when create class group, paid course and has ungrouped students
    fun valid(): List<Course> {
        val valid = courseMapper.list(WebSession.user().schoolId).filter { it.visible }

        // load ungrouped students
        valid.forEach {
            it.ungroupedStudents = orderMapper.ungroupedStudents(it.schoolId, it.id)
                .mapNotNull { sid -> userCache.get(sid) }
        }

        return valid.filter { it.ungroupedStudents.isNotEmpty() }
    }

    fun save(course: Course): Int {

        if (WebSession.user().schoolId != course.schoolId) {
            throw BizEx.of("参数异常，请重新登录")
        }

        if (course.id == 0) {
            courseMapper.insert(course)
        } else {
            courseMapper.update(course)
        }

        courseCache.invalidate(course.schoolId)

        return course.id
    }

    fun visible(id: Int, visible: Boolean) {
        val user = WebSession.user()
        if (user.role === PRINCIPAL) {
            courseMapper.updateVisible(id, user.schoolId, visible)
        }
    }
}
